<template>
	<view class="edit-container">
		<form @submit="handleSubmit">
			<view class="form-group">
				<view class="form-item">
					<text class="label">收货人</text>
					<input 
						class="input" 
						type="text" 
						v-model="formData.name" 
						placeholder="请输入收货人姓名"
						maxlength="20"
					/>
				</view>
				
				<view class="form-item">
					<text class="label">手机号码</text>
					<input 
						class="input" 
						type="number" 
						v-model="formData.phone" 
						placeholder="请输入手机号码"
						maxlength="11"
					/>
				</view>
				
				<view class="form-item">
					<text class="label">所在地区</text>
					<view class="picker-wrapper" @click="showRegionPicker">
						<text class="picker-text" :class="{ placeholder: !regionText }">
							{{ regionText || '请选择省市区' }}
						</text>
						<text class="picker-arrow">></text>
					</view>
				</view>
				
				<view class="form-item">
					<text class="label">详细地址</text>
					<textarea 
						class="textarea" 
						v-model="formData.detail" 
						placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
						maxlength="100"
					/>
				</view>
			</view>
			
			<view class="default-section">
				<view class="default-item" @click="toggleDefault">
					<text class="checkbox" :class="{ checked: formData.isDefault }">
						{{ formData.isDefault ? '✓' : '' }}
					</text>
					<text class="default-text">设为默认收货地址</text>
				</view>
			</view>
			
			<view class="submit-section">
				<button class="submit-btn" form-type="submit">保存</button>
			</view>
		</form>
		
		<!-- 地区选择器 -->
		<view class="region-picker" v-if="showPicker">
			<view class="picker-mask" @click="hideRegionPicker"></view>
			<view class="picker-content">
				<view class="picker-header">
					<text class="picker-cancel" @click="hideRegionPicker">取消</text>
					<text class="picker-title">选择地区</text>
					<text class="picker-confirm" @click="confirmRegion">确定</text>
				</view>
				<picker-view 
					class="picker-view" 
					:indicator-style="indicatorStyle"
					:value="pickerValue"
					@change="bindPickerChange"
				>
					<picker-view-column>
						<view 
							v-for="(item, index) in provinces" 
							:key="index" 
							class="picker-item"
						>
							{{ item.name }}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view 
							v-for="(item, index) in cities" 
							:key="index" 
							class="picker-item"
						>
							{{ item.name }}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view 
							v-for="(item, index) in districts" 
							:key="index" 
							class="picker-item"
						>
							{{ item.name }}
						</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>
</template>

<script>
import { addressApi } from '@/api/index.js'

export default {
	data() {
		return {
			addressId: null, // 地址ID，编辑时使用
			formData: {
				name: '',
				phone: '',
				province: '',
				city: '',
				district: '',
				detail: '',
				isDefault: false
			},
			showPicker: false,
			indicatorStyle: `height: 50px;`,
			pickerValue: [0, 0, 0],
			provinces: [],
			cities: [],
			districts: [],
			selectedProvince: null,
			selectedCity: null,
			selectedDistrict: null
		}
	},
	computed: {
		// 地区文本
		regionText() {
			if (this.formData.province && this.formData.city && this.formData.district) {
				return `${this.formData.province} ${this.formData.city} ${this.formData.district}`
			}
			return ''
		},
		// 获取登录状态
		isLogin() {
			return this.$store.getters.getIsLogin
		}
	},
	onLoad(options) {
		// 检查登录状态，未登录则跳转到登录页
		if (!this.isLogin) {
			// 获取当前页面路径作为重定向参数
			const currentPath = options.id ? `/pages/address/edit?id=${options.id}` : '/pages/address/edit'
			
			// 跳转到登录页
			uni.navigateTo({
				url: `/pages/login/login?redirect=${encodeURIComponent(currentPath)}`
			})
			return
		}
		
		// 如果有ID，则是编辑模式
		if (options.id) {
			this.addressId = options.id
			this.loadAddressDetail(options.id)
		}
		
		// 初始化省市区数据
		this.initRegionData()
	},
	methods: {
		// 加载地址详情
		async loadAddressDetail(id) {
			try {
				const res = await addressApi.getAddressDetail(id)
				const address = res.data
				this.formData = {
					name: address.name,
					phone: address.phone,
					province: address.province,
					city: address.city,
					district: address.district,
					detail: address.detail,
					isDefault: address.isDefault
				}
			} catch (error) {
				console.error('获取地址详情失败:', error)
				uni.showToast({
					title: '获取地址详情失败',
					icon: 'none'
				})
			}
		},
		
		// 初始化省市区数据
		initRegionData() {
			// 这里使用模拟数据，实际项目中应该从API获取
			this.provinces = [
				{ id: 1, name: '北京市' },
				{ id: 2, name: '上海市' },
				{ id: 3, name: '广东省' },
				{ id: 4, name: '浙江省' },
				{ id: 5, name: '江苏省' }
			]
			
			// 默认选择第一个省份
			this.selectedProvince = this.provinces[0]
			this.loadCities(0)
		},
		
		// 加载城市数据
		loadCities(provinceIndex) {
			this.selectedProvince = this.provinces[provinceIndex]
			
			// 模拟城市数据
			const cityData = {
				1: [{ id: 11, name: '北京市' }],
				2: [{ id: 21, name: '上海市' }],
				3: [
					{ id: 31, name: '广州市' },
					{ id: 32, name: '深圳市' },
					{ id: 33, name: '珠海市' }
				],
				4: [
					{ id: 41, name: '杭州市' },
					{ id: 42, name: '宁波市' }
				],
				5: [
					{ id: 51, name: '南京市' },
					{ id: 52, name: '苏州市' }
				]
			}
			
			this.cities = cityData[this.selectedProvince.id] || []
			
			// 默认选择第一个城市
			if (this.cities.length > 0) {
				this.selectedCity = this.cities[0]
				this.loadDistricts(0)
			}
		},
		
		// 加载区县数据
		loadDistricts(cityIndex) {
			this.selectedCity = this.cities[cityIndex]
			
			// 模拟区县数据
			const districtData = {
				11: [{ id: 111, name: '东城区' }, { id: 112, name: '西城区' }],
				21: [{ id: 211, name: '黄浦区' }, { id: 212, name: '徐汇区' }],
				31: [{ id: 311, name: '天河区' }, { id: 312, name: '越秀区' }],
				32: [{ id: 321, name: '南山区' }, { id: 322, name: '福田区' }],
				41: [{ id: 411, name: '西湖区' }, { id: 412, name: '上城区' }],
				51: [{ id: 511, name: '鼓楼区' }, { id: 512, name: '玄武区' }]
			}
			
			this.districts = districtData[this.selectedCity.id] || []
			
			// 默认选择第一个区县
			if (this.districts.length > 0) {
				this.selectedDistrict = this.districts[0]
			}
		},
		
		// 显示地区选择器
		showRegionPicker() {
			this.showPicker = true
		},
		
		// 隐藏地区选择器
		hideRegionPicker() {
			this.showPicker = false
		},
		
		// 选择器变化
		bindPickerChange(e) {
			const val = e.detail.value
			this.pickerValue = val
			
			// 当省份变化时，重新加载城市
			if (val[0] !== this.provinces.indexOf(this.selectedProvince)) {
				this.loadCities(val[0])
				this.pickerValue = [val[0], 0, 0]
			}
			// 当城市变化时，重新加载区县
			else if (val[1] !== this.cities.indexOf(this.selectedCity)) {
				this.loadDistricts(val[1])
				this.pickerValue = [val[0], val[1], 0]
			}
			// 当区县变化时，更新选中的区县
			else if (val[2] < this.districts.length) {
				this.selectedDistrict = this.districts[val[2]]
			}
		},
		
		// 确认选择地区
		confirmRegion() {
			if (this.selectedProvince && this.selectedCity && this.selectedDistrict) {
				this.formData.province = this.selectedProvince.name
				this.formData.city = this.selectedCity.name
				this.formData.district = this.selectedDistrict.name
			}
			this.hideRegionPicker()
		},
		
		// 切换默认地址
		toggleDefault() {
			this.formData.isDefault = !this.formData.isDefault
		},
		
		// 表单验证
		validateForm() {
			if (!this.formData.name.trim()) {
				uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				})
				return false
			}
			
			if (!this.formData.phone.trim()) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				})
				return false
			}
			
			if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				})
				return false
			}
			
			if (!this.formData.province || !this.formData.city || !this.formData.district) {
				uni.showToast({
					title: '请选择所在地区',
					icon: 'none'
				})
				return false
			}
			
			if (!this.formData.detail.trim()) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				})
				return false
			}
			
			return true
		},
		
		// 提交表单
		async handleSubmit() {
			if (!this.validateForm()) return
			
			try {
				if (this.addressId) {
					// 编辑地址
					await addressApi.updateAddress(this.addressId, this.formData)
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					})
				} else {
					// 新增地址
					await addressApi.addAddress(this.formData)
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					})
				}
				
				// 延迟返回，让用户看到提示
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} catch (error) {
				console.error('保存地址失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style scoped>
.edit-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 100rpx;
}

.form-group {
	background-color: #fff;
	margin-top: 20rpx;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
	border-bottom: none;
}

.label {
	width: 160rpx;
	font-size: 30rpx;
	color: #333;
}

.input {
	flex: 1;
	font-size: 30rpx;
}

.textarea {
	flex: 1;
	font-size: 30rpx;
	height: 120rpx;
}

.picker-wrapper {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.picker-text {
	font-size: 30rpx;
	color: #333;
}

.picker-text.placeholder {
	color: #999;
}

.picker-arrow {
	font-size: 30rpx;
	color: #999;
}

.default-section {
	background-color: #fff;
	margin-top: 20rpx;
	padding: 30rpx;
}

.default-item {
	display: flex;
	align-items: center;
}

.checkbox {
	width: 40rpx;
	height: 40rpx;
	border: 2rpx solid #ddd;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
	font-size: 24rpx;
	color: #fff;
}

.checkbox.checked {
	background-color: #d81e06;
	border-color: #d81e06;
}

.default-text {
	font-size: 30rpx;
	color: #333;
}

.submit-section {
	margin-top: 60rpx;
	padding: 0 30rpx;
}

.submit-btn {
	background-color: #d81e06;
	color: #fff;
	height: 90rpx;
	line-height: 90rpx;
	border-radius: 45rpx;
	font-size: 32rpx;
}

/* 地区选择器样式 */
.region-picker {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
}

.picker-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
}

.picker-content {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
}

.picker-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.picker-cancel, .picker-confirm {
	font-size: 30rpx;
	color: #666;
}

.picker-confirm {
	color: #d81e06;
}

.picker-title {
	font-size: 32rpx;
	font-weight: bold;
}

.picker-view {
	width: 100%;
	height: 500rpx;
}

.picker-item {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
	font-size: 28rpx;
}
</style>